<?php
/**
 * Created by PhpStorm.
 * User: Lxx<779219930@qq.com>
 * Date: 2016/4/25
 * Time: 17:35
 */

namespace app\home\model;
use think\Model;

class WechatUser extends Model {
    /**
     * 微信帐号订阅
     * @param array $user
     */
    public function subscribe($user){
        // 检查是否已经有微信号订阅
        $where['openid'] = $user['openid'];
        $check = $this->where($where)->find();
        if(!empty($check)) {
            // 更新状态
            $data = array(
                'subscribe' => 1,
                'subscribe_time' => NOW_TIME,
                'unsubscribe_time' => 0
            );
            $this->where($where)->setField($data);
            $id = $check["id"];
        } else {
            // 添加用户
            $id = $this->create($user);
        }

        return $id;
    }

    /**
     * 微信帐号取消订阅
     * @param string $openid
     */
    public function unSubscribe($openid){
        $data = array(
            'subscribe' => 0,
            'unsubscribe_time' => NOW_TIME
        );
        $where['openid'] = $openid;
        $this->where($where)->setField($data);
    }

    public function checkUserExist($userId) {
        return $this->where('userId', $userId)->find();
    }

    public function departmentName() {

        return $this->hasOne("WechatDepartment","id","department");
    }
}